﻿using UnityEditor;
using UnityEngine;

public static class ImporterCommands
{
    [MenuItem("CONTEXT/ModelImporter/Skinn: Rename Clip From Asset(Experimental)", false, 1)]
    private static void ModelImporterRenameClipFromAsset(MenuCommand command)
    {
        var context = (ModelImporter)command.context;
        var go = AssetDatabase.LoadAssetAtPath(context.assetPath, typeof(GameObject));
        var clips = context.clipAnimations;

        foreach (var clip in clips)
        {
            clip.name = go.name;
            context.clipAnimations = clips;
            context.SaveAndReimport();
            break;
        }
    }

    [MenuItem("CONTEXT/TextureImporter/Skinn: Duplicate as Normal Map 0.03", false, 1)]
    private static void TextureImporterDuplicateAsNormalMap(MenuCommand command)
    {
        var context = (TextureImporter)command.context;
        DuplicateAsNormalMap(context, 0.03f);
    }

    [MenuItem("CONTEXT/TextureImporter/Skinn: Duplicate as Normal Map 0.03", true, 1)]
    private static bool CanTextureImporterDuplicateAsNormalMap(MenuCommand command)
    {
        var context = (TextureImporter)command.context;
        if (context.textureType == TextureImporterType.NormalMap) return false;
        return true;
    }

    [MenuItem("CONTEXT/TextureImporter/Skinn: Duplicate as Normal Map Default", false, 1)]
    private static void TextureImporterDuplicateAsNormalMap025(MenuCommand command)
    {
        var context = (TextureImporter)command.context;
        DuplicateAsNormalMap(context, 0.03f);
    }

    [MenuItem("CONTEXT/TextureImporter/Skinn: Duplicate as Normal Map Default", true, 1)]
    private static bool CanTextureImporterDuplicateAsNormalMap025(MenuCommand command)
    {
        var context = (TextureImporter)command.context;
        if (context.textureType == TextureImporterType.NormalMap) return false;
        return true;
    }

    private static void DuplicateAsNormalMap(TextureImporter context, float heightmapScale = 0.25f)
    {
        if (!context) return;
        if (context.textureType == TextureImporterType.NormalMap) return;

        var assetPath = context.assetPath;
        var ext = assetPath.Substring(assetPath.LastIndexOf('.'));
        var newPath = assetPath.Remove(assetPath.LastIndexOf('.')) + "_NormalMap" + ext;

        AssetDatabase.CopyAsset(context.assetPath, newPath);
        AssetDatabase.Refresh();
        var importer = TextureImporter.GetAtPath(newPath) as TextureImporter;

        importer.textureType = TextureImporterType.NormalMap;
        importer.convertToNormalmap = true;
        importer.heightmapScale = heightmapScale;
        importer.SaveAndReimport();

        Selection.activeObject = importer;
    }
}
